//
//  DDCkdaQuestion.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/7/25.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDCkdaQuestion.h"
#import "UIImageView+WebCache.h"
#import "MWPhotoBrowser.h"
#import "DDNetWorkAPIClient.h"
#import "DDQuestionAnswerList.h"
#import "DDQuestionAnswerReply.h"
#import "SKSTableViewCell.h"
#import "MJRefresh.h"

#import "UIView+LoadFromNib.h"
#import "DDAnswerReplyFootView.h"

#import "DDShareViewController.h"

#import "OptionImageView.h"
#import "DDZhuDaVC.h"

#define KEY_IMAGE @"IMAGE"
#define KEY_LABEL @"LABEL"
#define KEY_OPTION @"OPTION"
#define KEY_FILL @"FILL"
#define KEY_ANSWER_IMAGE @"ANSWER_IMAEG"
#define KEY_ANSWER_AUDIO @"ANSWER_AUDIO"

#define FILED_BODY_IMAGE @"IMAGE"
#define FILED_BODY_TEXT @"TEXT"

#define TOPIC_TYPE_FILL @"填空题"

@implementation DDCkdaQuestion
- (id)initWithFrame:(CGRect)frame andColorViewData:(TNColorViewData *)colorViewData {
    
    self = [super initWithFrame:frame andColorViewData:colorViewData];
    
    if (self) {
        // Initialization code
        
        _question = colorViewData.question;
        _page = colorViewData.page;
        _total = colorViewData.total;
        _topic = colorViewData.topic;
        _typeIndex = colorViewData.typeIndex;
        _woAnswer = colorViewData.woAnswer;
        
        _showAnswer = colorViewData.showAnswer;
        
        self.backgroundColor = [UIColor whiteColor];
        self.tableView = [[SKSTableView alloc] initWithFrame:CGRectMake(0, 64, self.bounds.size.width, self.bounds.size.height-64) style:UITableViewStyleGrouped];
        [self addSubview:self.tableView];
        //self.tableView.delegate = self;
        //self.tableView.dataSource = self;
        //self.tableView.SKSTableViewDelegate = self;
        [self.tableView setSKSTableViewDelegate:self];
        self.tableView.tableHeaderView = [self headerView];
        
        
         //DDAnswerReplyFootView *footView = [DDAnswerReplyFootView loadFromNib];
        //self.tableView.tableFooterView = [self footerView];
        
        
        
        [self createUI];
        [self createData];
    }
    
    return self;
}


- (void)createUI
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
//    [self.tableView addHeaderWithTarget:self action:@selector(reloadPostData)];
//    //#warning 自动刷新(一进入程序就下拉刷新)
//    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    if (!_woAnswer) {
        [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    }
    
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
//    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
//    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
//    self.tableView.headerRefreshingText = @"别再拉了,裤子要被拉下来了...";
    
    self.tableView.footerPullToRefreshText = @"上提可以刷新了";
    self.tableView.footerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.footerRefreshingText = @"别再拉了,裤子要被拉下来了...";
}

- (void)createData
{
    _datas = [NSMutableArray array];
    _topHeaderDict = [NSMutableDictionary dictionary];
    
    
    
    
    NSMutableArray *imageArray = [NSMutableArray array];
    //NSMutableArray *labelArray = [NSMutableArray array];

    NSMutableArray *optionArray = [NSMutableArray array];
    
    //DDTopicDataCellModel *model =  _topic.list[0];
    //DDTopicQuestion *question = model.questions[0];
    NSArray *bodyList = _question.body;
    _questionType = _question.typeName;
    
    optionArray = [NSMutableArray arrayWithArray:_question.options];
    
    
//    //提取分组数据
//    for (DDTopicQuestionBody *body in bodyList) {
//        if ([body.type isEqualToString:FILED_BODY_IMAGE]) {
//            [imageArray addObject:body.url];
//        }
//        if ([body.type isEqualToString:FILED_BODY_TEXT]) {
//            //[labelArray addObject:[NSString stringWithFormat:@"%ld.%@",(long)_page,body.text]];
//            _title = body.text;
//        }
//    }
//    if (!_title) {
//        _title = _topic.title;
//    }
    
    //提取分组数据
    int cc = 0;
    for (DDTopicQuestionBody *body in bodyList) {
        if ([body.type isEqualToString:FILED_BODY_IMAGE]) {
            [imageArray addObject:body.url];
        }
        if ([body.type isEqualToString:FILED_BODY_TEXT]) {
            //[labelArray addObject:[NSString stringWithFormat:@"%ld.%@",(long)_page,body.text]];
            if (cc == 0) {
                _title = [NSString stringWithFormat:@"%ld.%@",(long)_page,body.text];
                if (!_title) {
                    _title = _topic.title;
                }
            }else{
                _title = body.text;
            }
            cc++;
            [imageArray addObject:_title];
        }
    }
    
    
    
    [_topHeaderDict setValue:imageArray forKey:FILED_BODY_IMAGE];
    
    //分组
//    if (imageArray.count > 0) {
//        [_datas addObject:_topHeaderDict];
//    }
    if (optionArray.count > 0) {
        [_topHeaderDict setValue:optionArray forKey:KEY_OPTION];
    }
    if ([_questionType isEqualToString:TOPIC_TYPE_FILL]) {
        [_topHeaderDict setValue:@[] forKey:KEY_FILL];
    }
    
    
    [_datas addObject:_topHeaderDict];
    
    [self.tableView reloadData];
    
    
    _pageSize = 10;
    _pageIndex = 0;
   
    __weak DDCkdaQuestion *weakSelf = self;
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [MBProgressHUD showMessag:@"正在加载回答列表" toView:self];
    [network mainQuestionAnswerList:@{@"topicId":_topic.id,@"qid":_question.id,@"pageIndex":[NSString stringWithFormat:@"%d",_pageIndex],@"pageSize":[NSString stringWithFormat:@"%d",_pageSize]} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        
        
        DDQuestionAnswerList *mylist = (DDQuestionAnswerList*)object;
        NSArray *my = mylist.list;
        NSMutableArray *list = [NSMutableArray arrayWithArray:my];
        if (my.count > 0) {
            DDQuestionAnswerListCell *cell = my[0];
            [network mainQuestionReplyList:@{@"answerId":cell.id} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
                
                DDQuestionAnswerReply *reply = (DDQuestionAnswerReply *)object;
                
                //追问&追答 ruanch 
                NSMutableArray * addArray = [NSMutableArray array];
                for (int i = 0; i < reply.list.count; i++) {
                    
                    DDQuestionAnswerReplyCell *cell = reply.list[i];
                //for (DDQuestionAnswerReplyCell *cell in reply.list) {
                    [addArray addObject:cell];
                    if (cell.children.count > 0) {
                        for (int j = 0; j < cell.children.count; j++) {
                
                        DDQuestionAnswerReplyCell *childer = cell.children[j];
                        [addArray addObject:childer];
                            
                        }
                    }
                }
                
                [list addObjectsFromArray:addArray];
                
                NSMutableArray *secondArray = [NSMutableArray array];
                [secondArray addObject:list];
                [weakSelf.datas addObject:secondArray];
                [weakSelf.tableView reloadData];
            }];
        }
        if (!_woAnswer) {
        [network mainQuestionAnswerList:@{@"topicId":_topic.id,@"qid":_question.id,@"excludedUid":@"123",@"pageIndex":[NSString stringWithFormat:@"%d",_pageIndex],@"pageSize":[NSString stringWithFormat:@"%d",_pageSize]} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            
            DDSharedUser *user = [DDSharedUser shared];
            DDUser *userinfo = user.userInfo;
            
            
            
            NSMutableArray *filter = [NSMutableArray array];
            DDQuestionAnswerList *answerlist = (DDQuestionAnswerList*)object;
            
            for (DDQuestionAnswerListCell *cell in answerlist.list) {
                if (![userinfo.uid isEqualToString: cell.uid]) {
                    [filter addObject:cell];
                    
                }else{
                   
                }
            }
            
            [weakSelf.datas addObjectsFromArray:filter];
            [weakSelf.tableView reloadData];
        }];
            
        }
    }];

    
}


#pragma mark - 私有方法

-(void)footerRereshing
{
    _pageIndex++;
    __weak DDCkdaQuestion *weakSelf = self;
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [network mainQuestionAnswerList:@{@"topicId":_topic.id,@"qid":_question.id,@"excludedUid":@"123",@"pageIndex":[NSString stringWithFormat:@"%d",_pageIndex],@"pageSize":[NSString stringWithFormat:@"%d",_pageSize]} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        
        DDQuestionAnswerList *answerlist = (DDQuestionAnswerList*)object;
        
        [weakSelf.datas addObjectsFromArray:answerlist.list];
        [weakSelf.tableView reloadData];
        [weakSelf.tableView footerEndRefreshing];
    }];
}


- (UIView *)headerView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 32)];
    view.backgroundColor = RGB(248, 248, 248);
    
    UILabel *pageLabel = [[UILabel alloc] initWithFrame:CGRectMake( self.frame.size.width/2-5,5,self.frame.size.width , 32)];
    pageLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)_page,(long)_total];
    [view addSubview:pageLabel];
    return view;
}



#pragma mark -UITableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id obj = self.datas[section];
    if ([obj isKindOfClass:[NSArray class]]) {
        return ((NSArray *)obj).count;
    }
    return 1;
    //return [self.datas[section] count];;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datas.count;
}

- (NSInteger)tableView:(SKSTableView *)tableView numberOfSubRowsAtIndexPath:(NSIndexPath *)indexPath
{
    id obj = self.datas[indexPath.section];
    if ([obj isKindOfClass:[NSArray class]]) {
        int i = [self.datas[indexPath.section][indexPath.row] count] ;
        return i - 1;
    }
    return 0;
}

//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    
//    if (section == 0 && ![_topic.type isEqualToString:@"1"] && !_woAnswer) {
////        if ([_topic.type isEqualToString:@"0"]) {
////           return  [self submitTimu];
////        }else{
////            if ([_topic.answerNumber integerValue] != [_topic.maxRewardNumber integerValue]) {
////                return  [self submitTimu];
////            }
////        }
//        
//    }
//    return nil;
//}

//查看详情页cell的底部第二版设为隐藏
- (DDAnswerReplyFootView *)submitTimu
{
    DDAnswerReplyFootView *footView = [DDAnswerReplyFootView loadFromNib];
    footView.submitAnswer = ^{
        [self gotoDetailPage];
    };
    footView.shareBtn = ^{
        //[DDShareViewController showShareWithController:self.superclass];
    };
    return footView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    //第二版没有底部设为隐藏
    if (section == 0) {
        return 0;
    }
    
    return 10;
}


- (void)gotoDetailPage
{
    DDTopicDataCellModel *topicModel = _topic;
    DDTopicDataCellModel * _model = topicModel;
    NSArray *questions = topicModel.questions;
    _questions = questions;
    
    
    
    NSMutableArray *qustionViews = [NSMutableArray array];
    for (int i = 0; i < _questions.count; i++)
    {
        DDTopicQuestion *question = _questions[i];
        TNColorViewData *viewData = [[TNColorViewData alloc] initWithCustomClass:[DDQuestionView class]];
        viewData.topic = _topic;
        viewData.question = question;
        viewData.page = i+1;
        viewData.total = questions.count;
        [qustionViews addObject:viewData];
    }
    //////////////////////////////////////
    
    TNColorScrollViewConfig *config = [[TNColorScrollViewConfig alloc] initWithColorDataObjects:qustionViews bounces:YES showsHorizontalScrollIndicator:NO showsVerticalScrollIndicator:NO pagingEnabled:YES scrollHorizontal:YES];
    
    self.colorScrollVC = [[TNColorScrollViewController alloc] initWithColorScrollViewConfig:config displayMedia:YES cssStyle:DDCSSStyleAnswer];
    self.colorScrollVC.topicID = _model.id;
    self.colorScrollVC.topicType = _topic.type;
    self.colorScrollVC.topic = _topic;
    
    self.colorScrollVC.isDisplayMedia = YES;
    self.colorScrollVC.currentScrollerPage = ^(NSInteger currentPage){
        //NSLog(@"%d",currentPage);
    };
    __weak DDCkdaQuestion *weakSelf = self;
    self.colorScrollVC.preScrollerPage = ^(NSInteger prePage){
        [weakSelf saveTimu:prePage];
    };
    self.colorScrollVC.currentScrollerPage = ^(NSInteger curPage){
        [weakSelf saveTimu:curPage];
    };
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:self.colorScrollVC];
}

-(void)saveTimu:(NSInteger)page
{
    DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
    DDTopicQuestion *question = self.questions[page];
    DDQuestionView *questionView =  self.colorScrollVC.view.scrollView.subviews[page];
    
    
    //答案集合上传
    NSString *explanationJson=@"";
    NSArray *answers = questionView.answers;
    NSMutableArray *explanations = [NSMutableArray array];
    for (int i = 0; i < answers.count ; i++) {
        NSString *ext = [answers[i] pathExtension];
        if ([ext isEqualToString:@"jpg"]) {
            
            //保存泡泡标签
            NSArray *tags =   [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' AND tagIndex='%d'",question.id,i] orderBy:nil offset:0 count:0];
            NSMutableArray *tagLabels = [NSMutableArray array];
            
            for (DDTagDB *tagdb in tags) {
                if ([tagdb.type isEqualToString:@"IMAGE"]||[tagdb.type isEqualToString:@"AUDIO"]) {
                    NSDictionary *dict = @{@"type":[tagdb.type isEqualToString:@"AUDIO"]?@"VOICE":tagdb.type,@"x":tagdb.x,@"y":tagdb.y,@"url":tagdb.result};
                    [tagLabels addObject:dict];
                }else if ([tagdb.type isEqualToString:@"TEXT"]){
                    NSDictionary *dict = @{@"type":tagdb.type,@"x":tagdb.x,@"y":tagdb.y,@"text":tagdb.result};
                    [tagLabels addObject:dict];
                }
            }
            NSDictionary *pngDict = @{@"type":@"IMAGE",@"url":answers[i],@"labels":tagLabels};
            [explanations addObject:pngDict];
        }
        if ([ext isEqualToString:@"caf"]) {
            NSDictionary *cafDict = @{@"type":@"VOICE",@"url":answers[i]};
            [explanations addObject:cafDict];
        }
        NSError *error;
        NSData * JSONData = [NSJSONSerialization dataWithJSONObject:explanations
                                                            options:kNilOptions
                                                              error:&error];
        explanationJson = [[NSString alloc]initWithData:JSONData encoding:NSUTF8StringEncoding];
    }
    
    
    NSString *result = questionView.result;
    [netwrok mainAnswerSave:@{@"topicId":_topic.id,@"qid":question.id,@"answer":result==nil?@"":result,@"costSeconds":@"10",@"explanations":explanationJson} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        NSLog(@"%@",object);
        if (object) {
            
        }
        [MBProgressHUD showMessag:message toView:self];
        
    }];
}

- (CGFloat)getCellHeightForTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath
{
    int height = 130;
    if (indexPath.section == 0) {
        
        height = 90;
        NSDictionary *dict = _datas[indexPath.section];
        NSArray *images = [dict objectForKey:KEY_IMAGE];
        NSArray *options = [dict objectForKey:KEY_OPTION];
        NSArray *fills = [dict objectForKey:KEY_FILL];
        //        if (_title) {
        //           height += [self autoLabelString:self.tableView string:_title].height;
        //        }
        
        if (images.count > 0) {
            //NSArray *array = [dict objectForKey:KEY_IMAGE];
            //height += 300 * array.count + 10;
            
            for (int i = 0; i < images.count; i++) {
                NSString *string = images[i];
                if ([string rangeOfString:@"http://"].location != NSNotFound &&([string rangeOfString:@"jpg"].location != NSNotFound || [string rangeOfString:@"png"].location != NSNotFound)) {
                    height += 300;
                }else{
                    height += [self autoLabelString:self.tableView string:string].height + 5;
                }
            }
            
            // height += 20;
            
            
            
        }
        if (options.count > 0)
        {
            NSArray *array = [dict objectForKey:KEY_OPTION];
            height += 54*array.count+80;
            
            for (DDTopicQuestionOption *option in array) {
                if (option.content.count > 0) {
                    DDTopicQuestionOptionContent *content = option.content[0];
                    height += [self autoLabelString2:tableView string:content.text].height;
                }
            }
        }
        if (fills.count > 0)
        {
            height += 200;
        }
    }else{
        height = 80;
        id obj = self.datas[indexPath.section];
        if ([obj isKindOfClass:[NSArray class]]) {
            
            id  object = self.datas[indexPath.section][0][indexPath.row];
            if (indexPath.row==0) {
                DDQuestionAnswerListCell *answerListCell = object;
                height += [self autoLabelString:self.tableView string:answerListCell.answer].height;
                
                NSArray *explanations = answerListCell.explanation;
                for (DDQuestionAnswerExplanation *explanation in explanations) {
                    if ([explanation.type isEqualToString:@"TEXT"]) {
                        height += [self autoLabelString:self.tableView string:explanation.text].height;
                    }
                    else if([explanation.type isEqualToString:@"IMAGE"])
                    {
                        height += 300;
                    }
                }
            }else{
                if ([object isMemberOfClass:[DDQuestionAnswerReplyCell class]]) {
                    DDQuestionAnswerReplyCell *reply = object;
                    if (reply.content && reply.content.count > 0) {
                        if (!(reply.children.count == 0 && [reply.parent integerValue] > 0)) {
                            height += 44;
                        }
                        
                        for (DDQuestionAnswerReplyContent *content in reply.content) {
                            if ([content.type isEqualToString:@"TEXT"]) {
                                height += [self autoLabelString:self.tableView string:content.text].height;
                            }
                            else if([content.type isEqualToString:@"IMAGE"])
                            {
                                height += 300;
                            }
                        }
                    }
                    
                }
                
            }
            
            
            
            
            
            
        }else{
            
            DDQuestionAnswerListCell *answerListCell = _datas[indexPath.section];
            id obj = self.datas[indexPath.section];
            if ([obj isKindOfClass:[NSArray class]]) {
                answerListCell = self.datas[indexPath.section][0][0];
                
            }else{
                answerListCell = _datas[indexPath.section];
            }
            //DDQuestionAnswerListCell *answerListCell = _datas[indexPath.section];
            height += [self autoLabelString:self.tableView string:answerListCell.answer].height;
            
            NSArray *explanations = answerListCell.explanation;
            for (DDQuestionAnswerExplanation *explanation in explanations) {
                if ([explanation.type isEqualToString:@"TEXT"]) {
                    height += [self autoLabelString:self.tableView string:explanation.text].height;
                }
                else if([explanation.type isEqualToString:@"IMAGE"])
                {
                    height += 300;
                }
            }
        }
    }
    return height;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return [self getCellHeightForTableView:tableView indexPath:indexPath];
}
- (CGSize)autoImage:(UIImage *)image
{
    float w = image.size.width/2;
    float h = image.size.height/2;
    if (w > self.tableView.frame.size.width - 10) {
        //tw/th = w/h = c;
        float c = (self.tableView.frame.size.width - 10)/w;
        float tw = self.tableView.frame.size.width - 10;
        float th = h*c;
        
        return CGSizeMake(tw, th);
    }else{
        return CGSizeMake(w, h);
    }
    
}

- (CGSize)autoLabelString2:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(view.frame.size.width - 100,2000);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}

- (CGSize)autoLabelString:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17.0];
    
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    
    NSDictionary * attributes = @{NSFontAttributeName : font,
                                  NSParagraphStyleAttributeName : paragraphStyle};
    
    CGSize contentSize = [s boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT)
                                         options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                      attributes:attributes
                                         context:nil].size;
    return contentSize;
    

    
//    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
//    //设置一个行高上限
//    CGSize size = CGSizeMake(view.frame.size.width - 10,2000);
//    //计算实际frame大小，并将label的frame变成实际大小
//    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
//    return labelsize;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    static NSString *identifier = @"UITableViewCell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        
//    }
    static NSString *CellIdentifier = @"SKSTableViewCell";
    
    SKSTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell)
        cell = [[SKSTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    if ([cell viewWithTag:8888]) {
        [[cell viewWithTag:8888] removeFromSuperview];
    }
    if ([cell viewWithTag:8889]) {
        [[cell viewWithTag:8889] removeFromSuperview];
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    
    if (indexPath.section == 0) {
        
        float MDHeight = 0;
        
        DDTopicDataCellModel *topicModel = _topic;
        NSArray *questions = topicModel.questions;
        float start_X = 5;
        float start_Y = 5;

        UIImageView *header_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(start_X, start_Y, 50, 50)];
        //header_imageView.image = [UIImage imageNamed:@"user_header"];
        [header_imageView sd_setImageWithURL:[NSURL URLWithString:topicModel.userAvatarUrl] placeholderImage:[UIImage imageNamed:@"首页列表头像-通用"]options:SDWebImageRefreshCached];
        header_imageView.layer.cornerRadius = 25.0;
        header_imageView.layer.masksToBounds = YES;
        [cell.contentView addSubview:header_imageView];
        
        UILabel *name_label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:header_imageView sp:10],header_imageView.frame.origin.y+5 , 200, 24)];
        name_label.text = topicModel.userName;
        name_label.textColor = RGB(124,203,203);
        [cell.contentView addSubview:name_label];
        
        UILabel *time_label = [[UILabel alloc] initWithFrame:CGRectMake(name_label.frame.origin.x,[self yPostiong:name_label sp:5] , 200, 16)];
        time_label.text = [self convertTime:topicModel.createTime];//@"1天前";
        time_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
        time_label.textColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:time_label];
        
        UIButton *typeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        typeButton.frame = CGRectMake(tableView.frame.size.width - 50, name_label.frame.origin.y+5, 50, 18);
        [typeButton setBackgroundImage:[UIImage imageNamed:@"icon_tag"] forState:UIControlStateNormal];
        
        NSString *typeName = topicModel.courseName;//questions.count > 0 ?((DDTopicQuestion *)questions[0]).typeName : @"";
        [typeButton setTitle:typeName forState:UIControlStateNormal];
        
        
        if (typeName) {
            typeButton.frame = CGRectMake(tableView.frame.size.width - [self autoSize:typeButton string:typeName].width, name_label.frame.origin.y+5, [self autoSize:typeButton string:typeName].width, 18);
        }
        
        typeButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:10.0];
        [typeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        ///[typeButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
        //[typeButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [cell.contentView addSubview:typeButton];

        
        
//        UILabel *gold_label = [[UILabel alloc] initWithFrame:CGRectMake(typeButton.frame.origin.x-(typeButton.frame.size.width/2),  name_label.frame.origin.y+3, 15, 16)];
//        gold_label.text = topicModel.reward;
//        gold_label.textAlignment = NSTextAlignmentLeft;
//        gold_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
//        gold_label.textColor = [UIColor orangeColor];
//        [cell.contentView addSubview:gold_label];
//        
//        
//        UIImageView *gold_imageview = [[UIImageView alloc] initWithFrame:CGRectMake([self xxPostiong:gold_label sp:5], name_label.frame.origin.y+5, 12, 12)];
//        gold_imageview.image = [UIImage imageNamed:@"icon_gold"];
//        [cell.contentView addSubview:gold_imageview];
//        
//        if (_typeIndex == 0 || _typeIndex == 2) {
//            gold_imageview.hidden = YES;
//            gold_label.hidden = YES;
//        }
        
        
//        UILabel *content_label = [[UILabel alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,[self yPostiong:header_imageView sp:10] , [self autoLabelString:self.tableView string:_title].width, [self autoLabelString:self.tableView string:_title].height+20)];
//        content_label.numberOfLines = 0;
//        content_label.font = [UIFont fontWithName:@"Arial" size:17.0];
//        content_label.text = _title;
//        [cell.contentView addSubview:content_label];
        
        //右上角参与人数
        UILabel *number_people_label = [[UILabel alloc] initWithFrame:CGRectMake(tableView.frame.size.width-60,[self yPostiong:name_label sp:3] , 200, 24)];
        number_people_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
        number_people_label.textColor = RGB(128, 128, 128);
        number_people_label.text = [NSString stringWithFormat:@"%@人回答",topicModel.answerNumber];
        [cell.contentView addSubview:number_people_label];
        
        //右上角悬赏金额按钮
        UILabel *gold_label = [[UILabel alloc] initWithFrame:CGRectMake(typeButton.frame.origin.x-(typeButton.frame.size.width/2),  name_label.frame.origin.y+3, 15, 16)];
        gold_label.text = topicModel.reward;
        gold_label.textAlignment = NSTextAlignmentLeft;
        gold_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
        gold_label.textColor = [UIColor orangeColor];
        [cell.contentView addSubview:gold_label];
        
        
        UIImageView *gold_imageview = [[UIImageView alloc] initWithFrame:CGRectMake([self xxPostiong:gold_label sp:5], name_label.frame.origin.y+5, 12, 12)];
        gold_imageview.image = [UIImage imageNamed:@"icon_gold"];
        [cell.contentView addSubview:gold_imageview];
        
        
        int startHeight = [self yPostiong:header_imageView sp:10];
        
        NSDictionary *dict = _datas[indexPath.section];
        NSArray *images = [dict objectForKey:KEY_IMAGE];
        NSArray *options = [dict objectForKey:KEY_OPTION];
        NSArray *fills = [dict objectForKey:KEY_FILL];
        
        if (images.count) {
            NSArray *array = images;
            _imageArray = images;
            for (int i = 0 ; i < array.count ; i++)
            {
                NSString *url = array[i];
                NSRange range = [url rangeOfString:@"http://"];//判断字符串是否包含
                if (range.length >0)//包含
                {
                    //startHeight = startHeight + (300*i);
                    
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, startHeight , tableView.frame.size.width - 20, 300)];
                    [imageView sd_setImageWithURL:[NSURL URLWithString:array[i]] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]options:SDWebImageRefreshCached];
                    [cell.contentView addSubview:imageView];
                    //imageView.contentMode =  UIViewContentModeScaleAspectFill;
                    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                    button.frame = imageView.frame;
                    [button addTarget:self action:@selector(handleSingleTapImage) forControlEvents:UIControlEventTouchUpInside];
                    startHeight += 300;
                    [cell.contentView addSubview:button];

                    
                }else{
                    NSString *string = array[i];
                    UILabel *content_label = [[UILabel alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,startHeight , [self autoLabelString:self.tableView string:string].width, [self autoLabelString:self.tableView string:string].height)];
                    content_label.numberOfLines = 0;
                    content_label.text = string;
                    content_label.font = [UIFont fontWithName:@"Arial" size:17.0];
                    
                    startHeight += [self autoLabelString:self.tableView string:string].height;
                    [cell.contentView addSubview:content_label];
                }
                
//                startHeight = startHeight + (300*i);
//                
//                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, startHeight , tableView.frame.size.width - 20, 300)];
//                [imageView sd_setImageWithURL:[NSURL URLWithString:array[i]] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]options:SDWebImageRefreshCached];
//                [cell.contentView addSubview:imageView];
//                //imageView.contentMode =  UIViewContentModeScaleAspectFill;
//                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//                button.frame = imageView.frame;
//                [button addTarget:self action:@selector(handleSingleTapImage) forControlEvents:UIControlEventTouchUpInside];
//                
//                [cell.contentView addSubview:button];
            }
           // startHeight += 300;
        }
        /////////////////////////////我要参加
        MDHeight = startHeight;
       
        if (options.count > 0)
        {
            
            NSArray *array = options;
            UILabel *typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, startHeight, tableView.frame.size.width, 32)];
            typeLabel.text = [NSString stringWithFormat:@"(%@)", _questionType];
            [cell.contentView addSubview:typeLabel];
            
            int oheight = [self yPostiong:typeLabel sp:10];
            //NSArray *storeOption = [_question.answer componentsSeparatedByString:@","];
            
            
            NSMutableArray *storeOption = [[NSMutableArray alloc] init];
            NSUInteger len = [_question.answer length];
            for(NSUInteger i=0; i<len; i++)
            {
                [storeOption addObject:[NSString stringWithFormat:@"%@",[_question.answer substringWithRange:NSMakeRange(i, 1)]]];
            }
            
            for (int i = 0; i < array.count; i++) {
                DDTopicQuestionOption *option = array[i];
                UIButton *optionButton = [UIButton buttonWithType:UIButtonTypeCustom];
                optionButton.frame = CGRectMake(10, oheight, 38, 38);
                [optionButton setTitle:option.label forState:UIControlStateNormal];
               
                
                if(_showAnswer && [_questionType isEqualToString:@"多选"]&&[_topic.type isEqualToString:@"1"]) {
                    for (int j = 0 ; j<storeOption.count; j++) {
                        if ([storeOption[j] isEqualToString:option.label]) {
                            [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-圆点选中_09"] forState:UIControlStateNormal];
                            break;
                        }else{
                            
                            [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-选项bg灰"] forState:UIControlStateNormal];
                            [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-选项bg橙"] forState:UIControlStateSelected];
                        }
                    }
                    
                }else{
                
                if (_showAnswer && [_question.answer isEqualToString:option.label]&&[_topic.type isEqualToString:@"1"] ){
                    
                        [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-圆点选中_09"] forState:UIControlStateNormal];
                    
                }else{
                    
                    [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-选项bg灰"] forState:UIControlStateNormal];
                    [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-选项bg橙"] forState:UIControlStateSelected];
                }
                }
                [optionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                optionButton.tag = i+1000;
                //[optionButton addTarget:self action:@selector(optionSelect:) forControlEvents:UIControlEventTouchUpInside];
                
                [cell.contentView addSubview:optionButton];
                
                
                if (option.content.count > 0) {
                   
                DDTopicQuestionOptionContent *content = option.content[0];
                if ([content.type isEqualToString:@"TEXT"])
                {
                    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:optionButton sp:10], optionButton.frame.origin.y-5, tableView.frame.size.width-100, [self autoLabelString2:tableView string:content.text].height+30)];
                    label.text = content.text;
                    label.numberOfLines = 0;
                    label.font = [UIFont fontWithName:@"Arial" size:17];
                    label.textColor = [UIColor blackColor];
                    [cell.contentView addSubview:label];
                    
                    oheight += [self autoLabelString2:tableView string:content.text].height+40;
                    MDHeight = oheight;
                    
                }
                else if ([content.type isEqualToString:@"IMAGE"])
                {
//                    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake([self xPostiong:optionButton sp:10], optionButton.frame.origin.y+5, 32, 32)];
//                    [imageView sd_setImageWithURL:[NSURL URLWithString:content.url] placeholderImage:[UIImage imageNamed:@"个人中心-人数统计头像"]options:SDWebImageRefreshCached];
//                    [cell.contentView addSubview:imageView];
                    
                    OptionImageView *imageView = [[OptionImageView alloc]initWithFrame:CGRectMake([self xPostiong:optionButton sp:10], optionButton.frame.origin.y+5, 32, 32)];
                    [imageView sd_setImageWithURL:[NSURL URLWithString:content.url] placeholderImage:[UIImage imageNamed:@"个人中心-人数统计头像"]options:SDWebImageRefreshCached];
                    imageView.tag = 8889;
                    imageView.url = content.url;
                    imageView.userInteractionEnabled = YES;
                    [cell addSubview:imageView];
                    tableView.delaysContentTouches = NO;
                    tableView.autoresizesSubviews = YES;
                    [cell.contentView bringSubviewToFront:imageView];
                    cell.userInteractionEnabled=YES;
                    
                    oheight+=42;
                    MDHeight = oheight;
                }
                }else{
                    oheight +=54;
                    MDHeight = oheight;
                }
                
            }
        }
        
//        UILabel *titleLabel = [[UILabel alloc] init];
        if (fills.count > 0) {
              UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, self.tableView.frame.size.width-10, 24)];
                titleLabel.text = _questionType;
                
                [cell.contentView addSubview:titleLabel];
                
                _fillTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, [self yPostiong:titleLabel sp:5], self.tableView.frame.size.width-10, 150)];
                _fillTextView.layer.borderWidth = 1.0;
                _fillTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
                _fillTextView.layer.cornerRadius = 10;
                _fillTextView.delegate = self;
                [cell.contentView addSubview:_fillTextView];
        
        }
    
//        =============================
        //创建我要参加按钮或者倒计时
        MDHeight = [self getCellHeightForTableView:tableView indexPath:indexPath];
        NSString *string = [self compareTimeStampWithSufTime:[_topic.startTime longLongValue]];
        NSLog(@"=========%@========", [self convertTime:_topic.startTime]);

        UIButton *wantToJoinBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        wantToJoinBtn.frame = CGRectMake(kDeviceWidth - 320, MDHeight - 40, 300, 35);
        [wantToJoinBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        
        //如果已经开始了
       if(!string)
       {
           [wantToJoinBtn setTitleColor:kRGB(0x2ebbeb) forState:UIControlStateNormal];
           [wantToJoinBtn addTarget:self action:@selector(onWantToJoinBtn:) forControlEvents:UIControlEventTouchUpInside];
           [wantToJoinBtn setTitle:@"我要参加" forState:UIControlStateNormal];
           [cell.contentView addSubview:wantToJoinBtn];
       }
        //如果还没开始
       else
       {
           [wantToJoinBtn setTitleColor:kRGB(0x2ebbeb) forState:UIControlStateNormal];
           [wantToJoinBtn setImage:[UIImage imageNamed:@"u76"] forState:UIControlStateNormal];
           [wantToJoinBtn setTitle:string forState:UIControlStateNormal];
           [cell.contentView addSubview:wantToJoinBtn];
       }
        

    }
    else//回答列表
    {
        DDQuestionAnswerListCell *questionCell = _datas[indexPath.section];
        id obj = self.datas[indexPath.section];
        if ([obj isKindOfClass:[NSArray class]]) {
           questionCell = self.datas[indexPath.section][0][0];
            if ([self.datas[indexPath.section][indexPath.row] count] - 1 > 0) {
                cell.isExpandable = YES;
            }
        }else{
            questionCell = _datas[indexPath.section];
            cell.isExpandable = NO;
        }
        
        float start_X = 5;
        float start_Y = 5;
        
        
        UIImageView *header_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(start_X, start_Y, 50, 50)];
        //header_imageView.image = [UIImage imageNamed:@"user_header"];
        [header_imageView sd_setImageWithURL:[NSURL URLWithString:questionCell.userAvatarUrl] placeholderImage:[UIImage imageNamed:@"首页列表头像-通用"]options:SDWebImageRefreshCached];
        header_imageView.layer.cornerRadius = 25.0;
        header_imageView.layer.masksToBounds = YES;
        [cell.contentView addSubview:header_imageView];
        
        UILabel *name_label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:header_imageView sp:10],header_imageView.frame.origin.y+5 , 200, 24)];
        if ([_topic.type isEqualToString:@"1"]) {
            name_label.text = questionCell.userName;
        }else{
            name_label.text = questionCell.nickName;
        }
        
        name_label.textColor = RGB(124,203,203);
        [cell.contentView addSubview:name_label];
        
        UILabel *time_label = [[UILabel alloc] initWithFrame:CGRectMake(name_label.frame.origin.x,[self yPostiong:name_label sp:5] , 200, 16)];
        time_label.text = questionCell.answerTime;//@"1天前";
        time_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
        time_label.textColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:time_label];
        
        
        
        
        UILabel *content_label = [[UILabel alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,[self yPostiong:header_imageView sp:10] , tableView.frame.size.width -10, [self autoLabelString:self.tableView string:questionCell.answer].height)];
        content_label.numberOfLines = 0;
        content_label.font = [UIFont fontWithName:@"Arial" size:17];
        content_label.text = questionCell.answer;
        [cell.contentView addSubview:content_label];
        
        
        int anwerHeight = [self yPostiong:content_label sp:10] ;
        NSArray *explanations = questionCell.explanation;
        for (DDQuestionAnswerExplanation *explanation in explanations) {
            if ([explanation.type isEqualToString:@"TEXT"]) {
                UILabel *content_label = [[UILabel alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,anwerHeight, tableView.frame.size.width -10, [self autoLabelString:self.tableView string:explanation.text].height)];
                content_label.numberOfLines = 0;
                content_label.text = explanation.text;
                content_label.font = [UIFont fontWithName:@"Arial" size:17];
                [cell.contentView addSubview:content_label];
                anwerHeight+=[self autoLabelString:self.tableView string:explanation.text].height;
            }
            else if([explanation.type isEqualToString:@"IMAGE"])
            {
                _answerImageArray = @[explanation.url];
                
               // DDMediaIV *answerImageView = [[DDMediaIV alloc] initWithFrame:CGRectMake(5,5,size.width, size.height)];
                
                NSArray *labels = explanation.labels;
//                for (DDQuestionAnswerLabelInfo *labelInfo in labels) {
//                    DDTagDB *tag = [[DDTagDB alloc] init];
//                    tag.x = labelInfo.x;
//                    tag.y = labelInfo.y;
//                    tag.type = labelInfo.type;
//                    if ([tag.type isEqualToString:@"TEXT"]) {
//                        tag.result = labelInfo.text;
//                    }else{
//                        tag.result = labelInfo.url;
//                    }
//                    tag.qid = _question.id;
//                }
                
                
                NSURL *url = [NSURL URLWithString:explanation.url];
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
                
                
                _tagimageView = [[DDMediaIV alloc] initWithFrame:CGRectMake(10, anwerHeight , tableView.frame.size.width - 20, 300)];
                _tagimageView.userInteractionEnabled = YES;
                _tagimageView.isOnlyRead = YES;
                _tagimageView.url = explanation.url;
                
                
               
                
                [_tagimageView sd_setImageWithURL:[NSURL URLWithString:explanation.url] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]options:SDWebImageRefreshCached];
                _tagimageView.tag = 8888;
                [cell  addSubview:_tagimageView];
                //imageView.contentMode =  UIViewContentModeScaleAspectFill;
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = _tagimageView.frame;
                //[button addTarget:self action:@selector(handleAnswerSingleTapImage) forControlEvents:UIControlEventTouchUpInside];
                //[cell.contentView addSubview:button];
                cell.contentView.userInteractionEnabled = NO;
                anwerHeight += 300;
                tableView.delaysContentTouches = NO;
                tableView.autoresizesSubviews = YES;
                [cell.contentView bringSubviewToFront:_tagimageView];
                cell.userInteractionEnabled=YES;
                for (DDQuestionAnswerLabelInfo *labelInfo in labels) {
                    double c_x = ([labelInfo.x integerValue]/image.size.width)*(tableView.frame.size.width - 20);
                    double c_y = ([labelInfo.y integerValue]/image.size.height)*300;
                    
                    [_tagimageView addMedia:labelInfo.text type:labelInfo.type x:c_x y:c_y url:labelInfo.url];
                }
                
            }

        }
    }

    
    return cell;
    
}

- (void)onWantToJoinBtn:(id)sender
{
    [self gotoDetailPage];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //什么都不做，或者不把触摸事件往下传递就行
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    //什么都不做，或者不把触摸事件往下传递就行
}

-(float) xxPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.origin.x - view.frame.size.width -  sp;
}

-(float) yyPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.origin.y - view.frame.size.height- sp;
}
- (CGSize)autoSize:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(1000,44);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"UITableViewCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    
    DDQuestionAnswerReplyCell * answerReply;
    //id Object = self.datas[indexPath.section][indexPath.row];
    for (id obj in self.datas[indexPath.section][indexPath.row]) {
        if ([obj isMemberOfClass:[DDQuestionAnswerReplyCell class]]) {
            answerReply = obj;
        }
    }
    
    if (answerReply) {
        DDQuestionAnswerReplyCell * answerReply = self.datas[indexPath.section][indexPath.row][indexPath.subRow];
        
        float start_X = 5;
        float start_Y = 5;
        
        
        UIImageView *header_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(start_X, start_Y, 50, 50)];
        //header_imageView.image = [UIImage imageNamed:@"user_header"];
        [header_imageView sd_setImageWithURL:[NSURL URLWithString:answerReply.userAvatarUrl] placeholderImage:[UIImage imageNamed:@"首页列表头像-通用"]options:SDWebImageRefreshCached];
        header_imageView.layer.cornerRadius = 25.0;
        header_imageView.layer.masksToBounds = YES;
        [cell.contentView addSubview:header_imageView];
        
        UILabel *name_label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:header_imageView sp:10],header_imageView.frame.origin.y+5 , 200, 24)];
        //name_label.text = answerReply.nickName;
        if ([_topic.type isEqualToString:@"1"]) {
            name_label.text = answerReply.userName;
        }else{
            name_label.text = answerReply.nickName;
        }
        name_label.textColor = RGB(124,203,203);
        [cell.contentView addSubview:name_label];
        
        UILabel *time_label = [[UILabel alloc] initWithFrame:CGRectMake(name_label.frame.origin.x,[self yPostiong:name_label sp:5] , 200, 16)];
        time_label.text = [self convertTime:answerReply.createTime];//@"1天前";
        time_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
        time_label.textColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:time_label];
    
        
        //追问&追答
        UIImageView * flagImageView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth([[UIScreen mainScreen] bounds]) - 80, 10, 60, 20)];
        flagImageView.image = [UIImage imageNamed:@"题目组背景"];
//        flagImageView.backgroundColor = [UIColor grayColor];
        [cell.contentView addSubview:flagImageView];
        
        UILabel * flagLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetWidth([[UIScreen mainScreen] bounds]) - 80, 10, 55, 20)];
        flagLabel.textColor = [UIColor whiteColor];
        flagLabel.textAlignment = NSTextAlignmentRight;
        flagLabel.font = [UIFont systemFontOfSize:14];
        
        
        [cell.contentView addSubview:flagLabel];
        
        
        NSArray *contents = answerReply.content;
        int height = [self yPostiong:header_imageView sp:10];
        for (DDQuestionAnswerReplyContent *content in contents) {
            if ([content.type isEqualToString:@"TEXT"]) {
                UILabel *content_label = [[UILabel alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,height , tableView.frame.size.width -10, [self autoLabelString:self.tableView string:content.text].height)];
                content_label.numberOfLines = 0;
                content_label.font = [UIFont fontWithName:@"Arial" size:17];
                content_label.text = content.text;
                [cell.contentView addSubview:content_label];
                height+=[self autoLabelString:self.tableView string:content.text].height;
            }else if([content.type isEqualToString:@"IMAGE"])
            {
                _answerImageArray = @[content.url];
                
                //bug 增加标签 ruanch
                NSURL *url = [NSURL URLWithString:content.url];
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
                DDMediaIV * imageView = [[DDMediaIV alloc] initWithFrame:CGRectMake(10, height , tableView.frame.size.width - 20, 300)];
                imageView.userInteractionEnabled = YES;
                imageView.isOnlyRead = YES;
                imageView.url = content.url;
//                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, height , tableView.frame.size.width - 20, 300)];
                [imageView sd_setImageWithURL:[NSURL URLWithString:content.url] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]options:SDWebImageRefreshCached];
                imageView.tag = 9999;
                [cell.contentView addSubview:imageView];
                //imageView.contentMode =  UIViewContentModeScaleAspectFill;
//                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//                button.frame = imageView.frame;
//                [button addTarget:self action:@selector(handleAnswerSingleTapImage) forControlEvents:UIControlEventTouchUpInside];
//                [cell.contentView addSubview:button];
                
                
                for (DDQuestionAnswerLabelInfo *labelInfo in content.labels) {
                    double c_x = ([labelInfo.x integerValue]/image.size.width)*(tableView.frame.size.width - 20);
                    double c_y = ([labelInfo.y integerValue]/image.size.height)*300;
                    
                    [imageView addMedia:labelInfo.text type:labelInfo.type x:c_x y:c_y url:labelInfo.url];
                }
                
                
                height += 300;
            }
        }
        

        if (answerReply.children.count == 0 && [answerReply.parent integerValue] > 0) {
            flagLabel.text = @"追答";
        }else{
            flagLabel.text = @"追问";
            
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"追答" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor grayColor] forState:UIControlStateSelected];
            [button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
            [button setImage:[UIImage imageNamed:@"icon_pen"] forState:UIControlStateNormal];
            button.frame = CGRectMake(-3, height, [UIScreen mainScreen].bounds.size.width+6, 44);
            button.titleLabel.textColor = [UIColor grayColor];
            button.backgroundColor = [UIColor clearColor];
            button.layer.borderColor = [UIColor grayColor].CGColor;
            button.layer.borderWidth = 0.5;
            
            
            button.tag = indexPath.section * 1000000 + indexPath.row * 1000 + indexPath.subRow;
            
            [button addTarget:self  action:@selector(zhuDa:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:button];
        }
        
    }
    
    
    
    
    return cell;
}

-(float) xPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.width+view.frame.origin.x + sp;
}

-(float) yPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.height+view.frame.origin.y + sp;
}

//- (NSString *)convertTime:(NSString *)time
//{
//    if (!time || [@"" isEqualToString:time]) {
//        return @"";
//    }
//    
//    
//    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
//    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
//    
//    long a =  [timeSp longLongValue] - time.longLongValue/1000;
//    
//    long day = a/(3600*24);
//    
//    if (day < 360 && day > 30) {
//        return [NSString stringWithFormat:@"%ld个月前",day/30];
//    }
//    else if (day >360){
//        return [NSString stringWithFormat:@"%ld年以前",day/360];
//    }
//    else if (day == 0)
//    {
//        long second = a/3600;
//        if (second > 0 && second < 24) {
//            return [NSString stringWithFormat:@"%ld小时前",second];
//        }else{
//            return [NSString stringWithFormat:@"%ld分钟前",a/60];
//        }
//        
//    }
//    else if (day > 1 && day < 6){
//        return [NSString stringWithFormat:@"%ld天前",day];
//    }else{
//        //实例化一个NSDateFormatter对象
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        //设定时间格式,这里可以设置成自己需要的格式
//        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//        //用[NSDate date]可以获取系统当前时间
//        NSDate *d = [NSDate dateWithTimeIntervalSince1970:time.longLongValue/1000];
//        NSString *dateStr = [dateFormatter stringFromDate:d];
//        return dateStr;
//    }
//    return @"";
//}

-(void)handleSingleTapImage
{
    NSLog(@"123123");
    _photos = [NSMutableArray array];
    
    for (int i = 0; i < _imageArray.count ; i++) {
        NSString *url = _imageArray[i];
        NSRange range = [url rangeOfString:@"http://"];//判断字符串是否包含
        if (range.length >0)//包含
        {
            MWPhoto   *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
            //photo.caption = _friendInfo.username;
            [_photos addObject:photo];
        }else{
            continue;
        }
    }
    
    [[NSNotificationCenter defaultCenter]  postNotificationName:@"DisPlayImage" object:_photos];

}
-(void)handleAnswerSingleTapImage
{
    NSLog(@"123123");
    _photos = [NSMutableArray array];
    
    for (int i = 0; i < _answerImageArray.count ; i++) {
        NSString *url = _answerImageArray[i];
        NSRange range = [url rangeOfString:@"http://"];//判断字符串是否包含
        if (range.length >0)//包含
        {
            MWPhoto   *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
            //photo.caption = _friendInfo.username;
            [_photos addObject:photo];
        }else{
            continue;
        }
    }
    
    [[NSNotificationCenter defaultCenter]  postNotificationName:@"DisPlayImage" object:_photos];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"123213");
}


//获取当前时间戳
- (NSTimeInterval)getCurrentTimeStamp
{
    NSDate *dataNow = [NSDate date];
    return [dataNow timeIntervalSince1970];
}

//对比时间戳，并返回差值,差值以倒计时方式显示
- (NSString *)compareTimeStampWithSufTime:(long long)sufTime
{
    if(sufTime == 0)
    {
        return nil;
    }
    long long preTime = (long long)([self getCurrentTimeStamp]*1000);
    long long dif = sufTime - preTime;
    //还没有到当天
    if(dif >= 0)
    {
        //天
        int day = (int)(dif/1000/(3600*24));
        //小时
        int hour = (int)(dif/1000%(3600*24)/3600);
        //分
        int minute = (int)((dif/1000%3600)/60);
        //秒
        int second = (int)(dif/1000%60);
        
        return [NSString stringWithFormat:@"%d天%d时%d分%d秒", day,hour, minute, second];
    }
    //已过期
    else
    {
        return nil;
    }
    
    return nil;
}

- (NSString *)convertTime:(NSString *)time
{
    if (!time || [@"" isEqualToString:time]) {
        return @"";
    }
    
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //用[NSDate date]可以获取系统当前时间
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:time.longLongValue/1000];
    NSString *dateStr = [dateFormatter stringFromDate:d];
    return dateStr;
    
    return @"";
}

- (void)zhuDa:(UIButton *)sender
{
    DDZhuDaVC *zhuDa = [[DDZhuDaVC alloc] initWithNibName:@"DDZhuDaVC" bundle:nil];
    
    NSInteger tag = sender.tag;
    
    NSInteger section = tag / 1000000;
    NSInteger row = (tag - (section*1000000))/1000;
    NSInteger subRow = (tag - ((section*1000000)+(row*1000)));
    DDQuestionAnswerReplyCell * answerReply = self.datas[section][row][subRow];
    zhuDa.reply = answerReply;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:zhuDa];
}

@end
